package com.example.zzl.adapter.HomeFragment;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.example.zzl.R;
import com.example.zzl.adapter.BasePagerAdapter;
import com.example.zzl.databinding.HomeItemvpVpBinding;
import com.example.zzl.model.bean.Home.OrderCommodity;
import com.example.zzl.utils.specification.VolleySingleton;

import java.util.List;

/**
 * Created by ligg on 2017/2/9.
 */

public class RecommendVpAdapter extends BasePagerAdapter<OrderCommodity.ResultBean> {

    private ImageView imageView;

    public RecommendVpAdapter(Context context, List<OrderCommodity.ResultBean> list) {
        super(context, list);
    }

    @Override
    public int getCount() {
        if (list != null && list.size() > 0) {
            return list.size() + 1;
        }
        return super.getCount();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        HomeItemvpVpBinding db = null;
        if (position != getCount() - 1) {
            OrderCommodity.ResultBean resultBean = list.get(position);
            db = DataBindingUtil.inflate(inflater, R.layout.home_itemvp_vp, container, false);
            db.setResult(resultBean);
            db.executePendingBindings();
            final ImageView iv = db.iv;
            iv.setTag(resultBean.strMainImage);
            VolleySingleton.volleySingleton.getImageLoader().get(resultBean.strMainImage, new ImageLoader.ImageListener() {
                @Override
                public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                    if (iv.getTag().equals(response.getRequestUrl())) {
                        iv.setImageBitmap(response.getBitmap());
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            datas[position] = db;
            container.addView(db.getRoot());
            return db.getRoot();
        } else {
            imageView = new ImageView(context);
            imageView.setImageResource(R.drawable.ic_launcher);
            return imageView;
        }
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (position != getCount() - 1) {
            super.destroyItem(container, position, object);
        } else {
            container.removeView(imageView);
        }
    }
}
